//
//  PlayerViewController.m
//  CloudPlayerDemo
//
//  Created by Ru He on 2022/2/25.
//

#import "PlayerViewController.h"
#import <HuaweiCloudPlayer/HuaweiCloudPlayer.h>
#import <HuaweiCloudPlayer/HCPConfig.h>

#define SCREENWIDTH [UIScreen mainScreen].bounds.size.width
#define SCREENHEIGHT [UIScreen mainScreen].bounds.size.height

@interface PlayerViewController ()<HuaweiCloudPlayerDelegate>
@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) HuaweiCloudPlayer *player;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic, strong) UIButton *play;

@end

@implementation PlayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.restrictRotation = YES;
    [self setDeviceInterfaceOrientation:UIDeviceOrientationLandscapeRight];
    
    [self createCloudPlayer];
    [self createContentViews];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    self.view.userInteractionEnabled = YES;
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    [self.view addGestureRecognizer:pan];
    
}

- (void)viewWillAppear:(BOOL)animated {
    
}

- (void)createCloudPlayer {
    if (self.player == nil) {
        // 配置播放器config对象
        HCPConfig *config = [[HCPConfig alloc] init];
        config.hardwareDecoder = YES;
        config.autoStart = YES;
        config.mediaType = self.playerInfo.mediaType;
        config.panoramic = YES;
        // 初始化播放器
        self.player = [[HuaweiCloudPlayer alloc] init];
        self.player.delegate = self;
        [self.player setConfig:config];
        [self.player prepareForUrl:self.playerInfo.mediaUrl];
    }
}

- (void)createContentViews {
    
    
    self.player.view.frame = CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT);
    [self.view addSubview:self.player.view];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(40, 30, 40, 40);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(pushBack:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    self.indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    self.indicatorView.frame = CGRectMake((SCREENWIDTH-30)/2, (SCREENHEIGHT-30)/2, 30, 30);
    [self.view addSubview:self.indicatorView];
    
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(80, SCREENHEIGHT - 70, SCREENWIDTH - 120, 20)];
    self.slider.userInteractionEnabled = NO;
    self.slider.minimumValue = 0;
    self.slider.maximumValue = 200;
    self.slider.continuous = NO;
    self.slider.minimumTrackTintColor = [UIColor blueColor];
    self.slider.maximumTrackTintColor = [UIColor grayColor];
    [self.slider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.slider];
    
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.slider.frame) - 150, CGRectGetMaxY(self.slider.frame), 150, 30)];
    self.timeLabel.backgroundColor = [UIColor clearColor];
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:self.timeLabel];
    
    self.play = [UIButton buttonWithType:UIButtonTypeCustom];
    self.play.frame = CGRectMake(40, SCREENHEIGHT - 75, 30, 30);
    [self.play setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
    [self.play addTarget:self action:@selector(PlayOrPause:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.play];
    
}

- (void)pushBack:(UIButton *)back {
    
    if (self.timer && [self.timer isValid]) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
    [self.player stop];
    [self.player destroy];
    [self.player.view removeFromSuperview];
    self.player.delegate = nil;
    self.player = nil;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)PlayOrPause:(UIButton *)btn {
    if (self.playerInfo.mediaType == MEDIA_TYPE_VOD) {
        if (self.player.isPlaying) {
            [self.player pause];
            [self.play setImage:[UIImage imageNamed:@"play.png"] forState:UIControlStateNormal];
        } else {
            [self.player start];
            [self.play setImage:[UIImage imageNamed:@"pause.png"] forState:UIControlStateNormal];
        }
    }
}

- (void)sliderValueChanged:(UISlider *)slider {
    [self.player seek:(slider.value*1000)];
}

- (void)handlePan:(UIPanGestureRecognizer *)pan {
    
    static CGPoint lastPoint;
    static int lastRotationDirect = 0;
    
    if (pan.state == UIGestureRecognizerStateChanged) {
        CGPoint translation = [pan translationInView:pan.view];
        
        if (translation.x - lastPoint.x < 0) {
            // 向左滑动
            [self.player setRotationDirection:-1];
            lastRotationDirect = -1;
        } else if (translation.x - lastPoint.x > 0) {
            // 向右滑动
            [self.player setRotationDirection:1];
            lastRotationDirect = 1;
        } else {
            [self.player setRotationDirection:lastRotationDirect];
        }
        
        
        lastPoint = translation;
        
        [pan reset];
    }
    
    if (pan.state == UIGestureRecognizerStateEnded) {
        [self.player stopRotating];
    }
}

- (void)willResignActive:(NSNotification *)notic {
    [self.player pause];
}

- (void)didBecomeActive:(NSNotification *)notic {
    [self.player start];
}

#pragma mark - HuaweiCloudPlayerDelegate -
- (void)onPrepared:(HuaweiCloudPlayer *)player {
    if (MEDIA_TYPE_VOD == self.playerInfo.mediaType) {
        self.slider.userInteractionEnabled = YES;
        self.slider.maximumValue = player.duration/1000;
        
        if (!self.timer) {
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
                if (!self.slider.tracking) {
                    self.slider.value = player.currentPosition/1000;
                }
                
                int iMin = (int)(round(player.currentPosition/1000) / 60.0);
                int iSec = (int)round(player.currentPosition/1000) % 60;
                
                if (iMin < 0) {
                    iMin = 0;
                }
                
                if (iSec < 0) {
                    iSec = 0;
                }
                
                if (!isnan(player.duration)) {
                    self.timeLabel.text = [NSString stringWithFormat:@"%02d:%02d | %02d:%02d", iMin, iSec, (int)((player.duration/1000) / 60), (int)(player.duration/1000) % 60];
                }
            }];
        }
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    }
}

- (void)onBufferingUpdate:(HuaweiCloudPlayer *)player percent:(int)percent {
    if (percent != 100) {
        [self.indicatorView startAnimating];
        self.indicatorView.hidden = NO;
    } else {
        [self.indicatorView stopAnimating];
        self.indicatorView.hidden = YES;
    }
}

- (void)onCompletion:(HuaweiCloudPlayer *)player {
    if (self.timer && [self.timer isValid]) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
    if (self.playerInfo.mediaType == MEDIA_TYPE_VOD) {
        self.slider.value = 0;
        [self.player prepareForUrl:self.playerInfo.mediaUrl];
    }
}

- (void)onError:(HuaweiCloudPlayer *)player code:(int)code description:(NSString *)description {
    NSString *message = [NSString stringWithFormat:@"%@(%d)", description, code];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"错误信息" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pushBack:nil];
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

@end
